package com.th.cash.th2.h5

import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.android.play.core.review.ReviewManagerFactory
import com.google.gson.Gson
import com.th.basemodel.base.BaseVB2Activity2
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.gotoActivity
import com.th.cash.th2.main.MainActivity
import com.th.cash.th2.userliving.UserLivingActivity
import com.th.cash.util.ActivityRouter
import com.th.cash.util.PointUtil
import com.th.resmodel.databinding.ActivityH5Binding

//网页
class H5Activity : BaseVB2Activity2<ActivityH5Binding>() {

    private var mUrl = ""

    private val mViewModel by viewModels<H5Vm>()

    private var uploadMessage: ValueCallback<Uri?>? = null
    private var uploadMessageAboveL: ValueCallback<Array<Uri?>>? = null
    private val FILE_CHOOSER_RESULT_CODE = 2001
    private var fileUri: Uri? = null

    companion object {
        var URL = "url"
    }

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    override fun setWindowPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun getDataFromIntent(intent: Intent) {
        mUrl = intent.getStringExtra(URL) ?: ""
    }

    override fun init() {
        initClick()
        initWebView()

        mBinding.webView.loadUrl(mUrl)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)

        uploadPoint()
    }

    private fun initClick() {
        mBinding.headBack.setOnClickListener {
            if (mBinding.webView.canGoBack()) {
                mBinding.webView.goBack()
            } else {
                finish()
            }
        }

        mBinding.headClose.setOnClickListener {
            finish()
        }
    }

    private fun initWebView() {
        mBinding.webView.settings.run {
            javaScriptEnabled = true // 默认false，设置true后我们才能在WebView里与我们的JS代码进行交互
            javaScriptCanOpenWindowsAutomatically = true // 设置JS是否可以打开WebView新窗口
            setSupportZoom(true) // 支持缩放
            builtInZoomControls = true // 支持手势缩放
            displayZoomControls = false // 不显示缩放按钮
            databaseEnabled = true //数据库存储API是否可用，默认值false。
            saveFormData = true //WebView是否保存表单数据，默认值true。
            domStorageEnabled = true //DOM存储API是否可用，默认false。
            setGeolocationEnabled(true) //定位是否可用，默认为true。
//          setAppCacheEnabled(true) //应用缓存API是否可用，默认值false, 结合setAppCachePath(String)使用。
            useWideViewPort = true // 将图片调整到适合WebView的大小
            loadWithOverviewMode = true // 自适应屏幕
            cacheMode = WebSettings.LOAD_NO_CACHE
            blockNetworkImage = true
        }


        mBinding.webView.run {
            isHorizontalScrollBarEnabled = false //去掉webview的滚动条,水平不显示
            isScrollbarFadingEnabled = true
            scrollBarStyle = View.SCROLLBARS_OUTSIDE_OVERLAY
            overScrollMode = View.OVER_SCROLL_NEVER // 取消WebView中滚动或拖动到顶部、底部时的阴影

            setLayerType(
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    View.LAYER_TYPE_HARDWARE
                } else {
                    View.LAYER_TYPE_SOFTWARE
                }, null
            )

            webViewClient = object : WebViewClient() {
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    mViewModel.loadStartLoading()
                }

                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    url?.let {
                        if (it.startsWith("http") || it.startsWith("https")) {
                            return super.shouldOverrideUrlLoading(view, url)
                        }
                        try {
                            val actions = arrayOf("mailto:", "geo:", "tel:", "sms:")
                            for (action in actions) {
                                if (url.startsWith(action)) {
                                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                                    startActivity(intent)
                                    return true
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                    }
                    return super.shouldOverrideUrlLoading(view, url)
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    mViewModel.loadSuccess()

                    mBinding.webView.settings.blockNetworkImage = false

                    view?.evaluateJavascript(
                        "document.title"
                    ) { p0 ->
                        // 处理获取到的标题
                        mBinding.headTitle.text = p0?.replace("\"", "") // 去掉引号
                    }
                }

                override fun onReceivedSslError(
                    view: WebView,
                    handler: SslErrorHandler,
                    error: SslError?
                ) {
                    super.onReceivedSslError(view, handler, error)

                    val builder = AlertDialog.Builder(view.context).run {
                        setMessage("ใบรับรองเว็บไซต์ไม่ถูกต้อง ดำเนินการต่อ?")
                        setPositiveButton(
                            "ยืนยัน"
                        ) { dialog, int -> handler.proceed(); }

                        setNegativeButton(
                            "ยกเลิก"
                        ) { dialog, int -> handler.cancel(); }

                        this
                    }
                    builder.create().show()
                }

                override fun onReceivedError(
                    view: WebView?,
                    request: WebResourceRequest?,
                    error: WebResourceError?
                ) {
                    super.onReceivedError(view, request, error)
                    mViewModel.loadSuccess()
                }
            }

            webChromeClient = object : WebChromeClient() {
                override fun onReceivedTitle(view: WebView?, t: String?) {
                    super.onReceivedTitle(view, t)

                    /*view?.postDelayed({
                        title = view.title
                    }, 200)*/
                }

                override fun onShowFileChooser(
                    webView: WebView?,
                    filePathCallback: ValueCallback<Array<Uri?>>?,
                    fileChooserParams: FileChooserParams?
                ): Boolean {
                    uploadMessageAboveL = filePathCallback;
                    openImageChooserActivity();
                    return true;
                }
            }

            addJavascriptInterface(Interface(this@H5Activity), "android")
        }
    }

    private fun openImageChooserActivity() {
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "image/*";//图片上传
//        i.setType("file/*");//文件上传
//        i.type = "*/*" //文件上传
        startActivityForResult(Intent.createChooser(i, "Chooser"), FILE_CHOOSER_RESULT_CODE)
    }

    // 3.选择图片后处理
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return
            val result = if (data == null || resultCode != RESULT_OK) null else data.data
            // Uri result = (((data == null) || (resultCode != RESULT_OK)) ? null : data.getData());
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data)
            } else if (uploadMessage != null) {
                uploadMessage!!.onReceiveValue(result)
                uploadMessage = null
            }
        } else {
            //这里uploadMessage跟uploadMessageAboveL在不同系统版本下分别持有了
            //WebView对象，在用户取消文件选择器的情况下，需给onReceiveValue传null返回值
            //否则WebView在未收到返回值的情况下，无法进行任何操作，文件选择器会失效
            if (uploadMessage != null) {
                uploadMessage!!.onReceiveValue(null)
                uploadMessage = null
            } else if (uploadMessageAboveL != null) {
                uploadMessageAboveL!!.onReceiveValue(null)
                uploadMessageAboveL = null
            }
        }
    }

    // 4. 选择内容回调到Html页面
    private fun onActivityResultAboveL(requestCode: Int, resultCode: Int, intent: Intent?) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) return
        var results: Array<Uri?>? = null
        if (resultCode == RESULT_OK) {
            if (intent == null) {
                results = arrayOf(fileUri)
            } else {
                val dataString = intent.dataString
                val clipData = intent.clipData
                if (clipData != null) {
                    results = arrayOfNulls(clipData.itemCount)
                    for (i in 0 until clipData.itemCount) {
                        val item = clipData.getItemAt(i)
                        results[i] = item.uri
                    }
                }
                if (dataString != null) results = arrayOf(Uri.parse(dataString))
            }
        }
        uploadMessageAboveL!!.onReceiveValue(results)
        uploadMessageAboveL = null
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mBinding.webView.canGoBack()) {
                mBinding.webView.goBack()
            } else {
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    var h5StartTime = 0L
    var h5EndTime = 0L

    private fun uploadPoint() {
        val str = Gson().toJson(PointUtil.getPoint(h5StartTime, h5EndTime, "", "6"))

        mBinding.webView.postDelayed({
            mBinding.webView.loadUrl("javascript:dasdasc2(${str})")
        }, 100)
    }


    class Interface(private val context: Context) {
        //获取埋点信息
        @JavascriptInterface
        fun dasdasc1(startTime: Long) {
            (context as H5Activity).run {
                h5StartTime = startTime
                uploadPoint()
            }
        }

        //拨打电话
        @JavascriptInterface
        fun dasdasc4(rebmunenohp: String) {
            val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$rebmunenohp"))
            context.startActivity(intent)
        }

        //App 首页
        @JavascriptInterface
        fun dasdasc15() {
            context.startActivity(Intent(context, MainActivity::class.java))
            (context as H5Activity).finish()
        }

        //App 应用评分
        @JavascriptInterface
        fun dasdasc16() {
            val manager = ReviewManagerFactory.create(context)
            val request = manager.requestReviewFlow()
            request.addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val reviewInfo = task.result
                    val flow = manager.launchReviewFlow(context as Activity, reviewInfo)
                    flow.addOnCompleteListener { _ ->
                        // 评分流程结束
                    }
                } else {
                    // 获取评分流程失败
                }
            }
        }

        //Appstore
        @JavascriptInterface
        fun dasdasc17(gkpppa: String) {
            try {
                context.startActivity(
                    Intent(
                        Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=$gkpppa")
                    )
                )
            } catch (e: ActivityNotFoundException) {
                context.startActivity(
                    Intent(
                        Intent.ACTION_VIEW,
                        Uri.parse("https://play.google.com/store/apps/details?id=$gkpppa")
                    )
                )
            }
        }

        //原生页面跳转
        @JavascriptInterface
        fun dasdasc18(url: String) {
            ActivityRouter.next(context, url)
        }

        @JavascriptInterface
        fun dasdasc110(pid: String?, endTime: Long) {
            if (TextUtils.isEmpty(pid)) {
                return
            }

            (context as H5Activity).h5EndTime = endTime

            context.gotoActivity<UserLivingActivity>(
                bundle = arrayOf<Pair<String, Any?>>(
                    Pair(UserLivingActivity.PID, pid)
                )
            )
        }
    }
}